/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import model.pojo.Comment;
import model.pojo.Post;
import model.pojo.User;
import model.pojo.util.helper;

/**
 *
 * @author Yasith
 */
public class fbComment {

    public static boolean addComment(User author, Post parentPost, String title, String text, String status) {

        EntityManager em = helper.getEMF().createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        Comment c = new Comment();
        c.setCommentStatus(status);
        c.setCommentText(text);
        c.setTimestamp(new Date());
        c.setUserId(author);
        c.setPostId(parentPost);

        em.persist(c);
        tx.commit();
        em.close();

        return true;
    }

    public static Collection<Comment> getComments(Post p) {
        EntityManager newEm = helper.getEMF().createEntityManager();
        EntityTransaction newTx = newEm.getTransaction();
        newTx.begin();
        Query query = newEm.createNamedQuery("Comment.findByPostId");
        query.setParameter("postId", p);
        List<Comment> c;
        try {
            c = (List<Comment>) query.getResultList();
        } catch (NoResultException ex) {
            c = null;
        }
        newTx.commit();
        newEm.close();

        return c;
    }

    public static boolean removeComment(int commentId) {
        EntityManager newEm = helper.getEMF().createEntityManager();
        EntityTransaction newTx = newEm.getTransaction();
        newTx.begin();
        Query query = newEm.createNamedQuery("Comment.findByCommentId");
        query.setParameter("commentId", commentId);
        Comment c;
        try {
            c = (Comment) query.getSingleResult();
        } catch (NoResultException ex) {
            c = null;
        }
        newEm.remove(c);

        newTx.commit();
        newEm.close();

        return true;
    }
    
        public static Comment getComment(int commentId) {
        EntityManager newEm = helper.getEMF().createEntityManager();
        EntityTransaction newTx = newEm.getTransaction();
        newTx.begin();
        Query query = newEm.createNamedQuery("Comment.findByCommentId");
        query.setParameter("commentId", commentId);
        Comment c;
        try {
            c = (Comment) query.getSingleResult();
        } catch (NoResultException ex) {
            c = null;
        }
        newTx.commit();
        newEm.close();

        return c;
    }
}
